﻿using MyWPF.Models.Recipe;
using MyWPF.StaticData;
using MyWPF.Views.Others;
using MyWPF.Views.Subpage.RecipePage_Son;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace MyWPF.ViewModel.Subpage
{
    public class VM_Recipe : BaseViewModel
    {
        public VM_Recipe()
        {
            #region 事件委托
            _loadedWindow = new DelegateCommand<object>(_LoadedWindow);
            _selectedCommand = new DelegateCommand<object>(_SelectedCommand);
            _deleteSingleRecipe = new DelegateCommand<object>(_DeleteSingleRecipe);
            _openAddRecipe = new DelegateCommand<object>(_OpenAddRecipe);
            _openModifyRecipe = new DelegateCommand<object>(_OpenModifyRecipe);
            #endregion


        }


        #region 属性绑定:表中数据
        /// <summary>
        /// 当前页内容
        /// </summary>
        public ObservableCollection<Recipe> TableData
        {
            get { return _tableData; }
            set
            {
                SetProperty(ref _tableData, value);
            }
        }
        private ObservableCollection<Recipe> _tableData;

        /// <summary>
        /// 用户选择行的内容
        /// </summary>
        public Recipe SelectedItem
        {
            get
            {
                return _selectedItem;
            }
            set
            {
                _selectedItem = value;
                if (value != null)
                {
                    LastSelected = value;
                }
                OnPropertyChanged("SelectedItem");

            }
        }
        private Recipe _selectedItem;
        private Recipe LastSelected;

        /// <summary>
        /// 当前应该显示的数据，和页面不进行绑定，但是只要改变它，页面就会跟着改变
        /// </summary>
        public DataTable RecipeDatas
        {
            get { return _recipeDatas; }
            set
            {
                TableData = new ObservableCollection<Recipe>();

                for (int i = 0; i < value.Rows.Count; i++)
                {
                    TableData.Add(new Recipe()
                    {

                        Name = Convert.ToString(value.Rows[i]["Name"]),
                        Owner = Convert.ToString(value.Rows[i]["Owner"]),
                        CreateTime = Convert.ToDateTime(value.Rows[i]["CreateTime"]),
                        ModifyTime = Convert.ToDateTime(value.Rows[i]["ModifyTime"]),
                        AllowControl = Convert.ToString(value.Rows[i]["AllowControl"]),
                        Remarks = Convert.ToString(value.Rows[i]["Remarks"])
                    }) ;
                }

                SetProperty(ref _recipeDatas, value);
            }
        }
        private DataTable _recipeDatas;

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string v)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(v));
            //throw new NotImplementedException();
        }
        #endregion
        #region 属性绑定：配方数据
        /// <summary>
        /// 配方数据
        /// </summary>
        public string RecipeData
        {
            get { return _recipeData; }
            set
            {
                SetProperty(ref _recipeData, value);
            }
        }
        private string _recipeData;
        /// <summary>
        /// 配方控件
        /// </summary>
        public UserControl RecipeContext
        {
            get { return _recipeContext; }
            set
            {
                SetProperty(ref _recipeContext, value);
            }
        }
        private UserControl _recipeContext;
        #endregion

        #region 事件绑定：页面加载事件
        /// <summary>
        /// 加载
        /// </summary>
        public ICommand LoadedWindow
        {
            get { return _loadedWindow; }
            set
            {
                _loadedWindow = value;
                OnPropertyChanged("LoadedWindow");
            }
        }
        private ICommand _loadedWindow;
        private void _LoadedWindow(object obj)
        {
            RefreshRecipe();
        }
        #endregion

        #region 事件绑定：选中配方后触发的事件
        /// <summary>
        /// 选中配方后触发的事件
        /// </summary>
        public ICommand SelectedCommand
        {
            get { return _selectedCommand; }
            set
            {
                _selectedCommand = value;
                OnPropertyChanged("SelectedCommand");
            }
        }
        private ICommand _selectedCommand;
        private void _SelectedCommand(object obj)
        {
            RecipeContext = new UserControl();
            StackPanel stackPanel1 = new StackPanel();

            RecipeContext[] Recipes = StaticModels.recipe.GetContextsStruct_Name(new RecipeContext()
            {
                Name = LastSelected.Name,
            });
            if (Recipes != null && Recipes.Length > 0)
            {
                RecipeData = JsonConvert.SerializeObject(Recipes[0].Data_1);
                Type type = typeof(Data_1);
                if (Recipes[0].Data_1 != null)
                {
                    foreach (var field in type.GetProperties())
                    {
                        object value = field.GetValue(Recipes[0].Data_1);
                        TextBlock textBlock1 = new TextBlock()
                        {
                            VerticalAlignment = System.Windows.VerticalAlignment.Center,
                            Text = field.Name + "：",
                        };
                        TextBlock textBlock2 = new TextBlock()
                        {
                            VerticalAlignment = System.Windows.VerticalAlignment.Center,
                            Text = value.ToString(),
                        };
                        StackPanel stackPanel2 = new StackPanel()
                        {
                            Orientation = Orientation.Horizontal,
                        };
                        stackPanel2.Children.Add(textBlock1);
                        stackPanel2.Children.Add(textBlock2);
                        stackPanel1.Children.Add(stackPanel2);
                    }
                }
                
                stackPanel1.Children.Add(new Button()
                {
                    Content = "修改",
                    Background = new SolidColorBrush(Color.FromArgb(0xff, 0x3b, 0xb1, 0x5d)),
                    Foreground = new SolidColorBrush(Color.FromArgb(0xff, 0xff, 0xff, 0xff)),
                    MinWidth = 200,
                    Margin = new System.Windows.Thickness(5),
                    Command = OpenModifyRecipe
                });
                RecipeContext.Content = stackPanel1;
                RecipeContext = RecipeContext;
            }
            else
            {
                RecipeData = String.Empty;
                RecipeContext = new UserControl();
            }
        }
        #endregion

        #region 事件绑定:打开配方窗口
        /// <summary>
        /// 打开添加配方窗口
        /// </summary>
        public ICommand OpenAddRecipe
        {
            get { return _openAddRecipe; }
            set
            {
                _openAddRecipe = value;
                OnPropertyChanged("OpenAddRecipe");
            }
        }
        private ICommand _openAddRecipe;
        private void _OpenAddRecipe(object obj)
        {
            StaticModels.motifyRecipe = new Views.Subpage.RecipePage_Son.MotifyRecipe();
            StaticModels.vM_MainWindow.Ambiguity = 5;
            StaticModels.motifyRecipe.ShowDialog();
            StaticModels.vM_MainWindow.Ambiguity = 0;
        }
        /// <summary>
        /// 打开修改配方窗口
        /// </summary>
        public ICommand OpenModifyRecipe
        {
            get { return _openModifyRecipe; }
            set
            {
                _openModifyRecipe = value;
                OnPropertyChanged("OpenModifyRecipe");
            }
        }
        private ICommand _openModifyRecipe;
        private void _OpenModifyRecipe(object obj)
        {
            RecipeContext[] Recipes = StaticModels.recipe.GetContextsStruct_Name(new Models.Recipe.RecipeContext()
            {
                Name = LastSelected.Name,
            });
            if (Recipes[0].OwnerPower >= StaticModels.user.User.PowerLevel && !Recipes[0].AllowControl && Recipes[0].Owner != StaticModels.user.User.UserName)
            {
                Tips tips = new Tips("当前用户没有权限修改该配方！");
                tips.ShowDialog();
                return;
            }
            if (Recipes.Length > 0)
            {
                StaticModels.motifyRecipe = new MotifyRecipe(Recipes[0]);
                StaticModels.vM_MainWindow.Ambiguity = 5;
                StaticModels.motifyRecipe.ShowDialog();
                StaticModels.vM_MainWindow.Ambiguity = 0;
            }
            
        }
        #endregion

        #region 事件绑定:表中删除按钮事件
        /// <summary>
        /// 表中删除按钮事件
        /// </summary>
        public ICommand DeleteSingleRecipe
        {
            get { return _deleteSingleRecipe; }
            set
            {
                _deleteSingleRecipe = value;
                OnPropertyChanged("DeleteSingleRecipe");
            }
        }
        private ICommand _deleteSingleRecipe;
        private void _DeleteSingleRecipe(object obj)
        {
            RecipeContext selectedRecipe = StaticModels.recipe.GetContextsStruct_Name(new RecipeContext()
            {
                Name = LastSelected.Name,
            })[0];
            if (selectedRecipe.OwnerPower >= StaticModels.user.User.PowerLevel && !selectedRecipe.AllowControl && selectedRecipe.Owner != StaticModels.user.User.UserName)
            {
                Tips tips = new Tips("当前用户没有权限删除该配方！");
                tips.ShowDialog();
                return;
            }
            ConfirmationWindow confirmationWindow = new ConfirmationWindow("是否删除该配方？");
            if ((bool)confirmationWindow.ShowDialog())
            {
                StaticModels.recipe.RemoveRecipe(new RecipeContext()
                {
                    Name = LastSelected.Name,
                });
                RefreshRecipe();
                //添加日志
                StaticModels.journal.AddJournal(new Models.Journal.JournalContext()
                {
                    Context = "删除配方'" + LastSelected.Name + "'",
                    User = StaticModels.user.User.UserName
                });

            }

        }
        #endregion

        #region 子事件：刷新配方
        public void RefreshRecipe()
        {
            RecipeContext[] Recipes = StaticModels.recipe.GetContextsStruct();
            RecipeDatas = new DataTable();
            RecipeDatas.Columns.Add("Name", typeof(string));
            RecipeDatas.Columns.Add("Owner", typeof(string));
            RecipeDatas.Columns.Add("CreateTime", typeof(DateTime));
            RecipeDatas.Columns.Add("ModifyTime", typeof(DateTime));
            RecipeDatas.Columns.Add("AllowControl", typeof(string));
            RecipeDatas.Columns.Add("Remarks", typeof(string));
            for (int i = 0; i < Recipes.Length; i++)
            {
                DataRow newRow = RecipeDatas.NewRow();
                newRow["Name"] = Recipes[i].Name;
                newRow["Owner"] = Recipes[i].Owner;
                newRow["CreateTime"] = Recipes[i].CreateTime;
                newRow["ModifyTime"] = Recipes[i].ModifyTime;
                newRow["AllowControl"] = Recipes[i].AllowControl;
                newRow["Remarks"] = Recipes[i].Remarks;
                RecipeDatas.Rows.Add(newRow);
            }


            RecipeDatas = RecipeDatas;
        }
        #endregion
    }


    public class Recipe
    {
        /// <summary>
        /// 配方名
        /// </summary>
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
            }
        }
        private string _name;

        /// <summary>
        /// 用户
        /// </summary>
        public string Owner
        {
            get
            {

                return _owner;
            }
            set
            {
                _owner = value;
            }
        }
        private string _owner;

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreateTime
        {
            get { return _createTime; }
            set { _createTime = value; }
        }
        private DateTime _createTime;

        /// <summary>
        /// 上一次修改时间
        /// </summary>
        public DateTime ModifyTime
        {
            get { return _modifyTime; }
            set { _modifyTime = value; }
        }
        private DateTime _modifyTime;


        /// <summary>
        /// 备注
        /// </summary>
        public string AllowControl
        {
            get { return _allowControl; }
            set { _allowControl = value; }
        }
        private string _allowControl;

        /// <summary>
        /// 备注
        /// </summary>
        public string Remarks
        {
            get { return _remarks; }
            set { _remarks = value; }
        }
        private string _remarks;
    }
}
